import {Injectable} from '@angular/core';
import {SmarketHttpService} from './smarket-http.service';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class ArticleListService {

  constructor(private smarketHttpService: SmarketHttpService) {
  }

  getArticleColumn(params: object): Observable<(Article | Column)[]> {
    return this.smarketHttpService.post('articleCategory.search', params).map(res => {
      const _list: any[] = res.content.items,
        list: (Column | Article)[] = [];
      _list.forEach(item => {
        if (item.hasOwnProperty('articleCategoryId')) {
          list.push(new Column(item.articleCategoryId, item.title, item.createTime, item.articleCount));
        } else if (item.hasOwnProperty('articleId')) {
          list.push(new Article(item.articleId, item.title, item.createTime));
        }
      });
      return list;
    });
  }

  addArticle(params: object): Observable<boolean> {
    return this.smarketHttpService.post('article.create', params).map(data => {
      return data.result.toString() === '0';
    });
  }
}

export class Article {
  constructor(
    public articleId: string,
    public title: string,
    public createTime: string) {
  }
}

export class Column {
  constructor(
    public articleCategoryId: string,
    public title: string,
    public createTime: string,
    public articleCount: string) {
  }
}
